package com.smart4j.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * JSON工具类
 *
 * @author 段誉
 * @create 2019-04-01 19:27
 */
@Slf4j
public final class JsonUtil {
  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  /**
   * 将POJO转为JSON
   */
  public static <T> String toJson(T obj) {
    String json;
    try {
      json = OBJECT_MAPPER.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      log.error("convert POJO to JSON failure", e);
      throw new RuntimeException(e);
    }
    return json;
  }

  /**
   * 将json转为pojo
   */
  public static <T> T fromJson(String json, Class<T> type) {
    T pojo;
    try {
      pojo = OBJECT_MAPPER.readValue(json, type);
    } catch (Exception e) {
      log.error("convert JSON to POJO failure", e);
      throw new RuntimeException(e);
    }
    return pojo;
  }
}
